<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OTA 升级文件上传</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .upload-section, .status-section, .files-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .upload-section h2, .status-section h2, .files-section h2 {
            color: #555;
            margin-top: 0;
        }
        .file-input {
            margin: 15px 0;
        }
        .file-input input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 2px dashed #ddd;
            border-radius: 5px;
        }
        .upload-btn, .refresh-btn, .cleanup-btn, .install-btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        .upload-btn:hover, .refresh-btn:hover {
            background-color: #0056b3;
        }
        .cleanup-btn {
            background-color: #dc3545;
        }
        .cleanup-btn:hover {
            background-color: #c82333;
        }
        .install-btn {
            background-color: #28a745;
        }
        .install-btn:hover {
            background-color: #218838;
        }
        .upload-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .progress {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            margin: 15px 0;
            display: none;
        }
        .progress-bar {
            height: 100%;
            background-color: #007bff;
            width: 0%;
            transition: width 0.3s ease;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }
        .result.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .result.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status-info {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .files-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .file-item:last-child {
            border-bottom: none;
        }
        .file-info {
            flex: 1;
        }
        .file-name {
            font-weight: bold;
            color: #333;
        }
        .file-details {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        .api-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-top: 20px;
        }
        .api-section h3 {
            color: #333;
            margin-top: 0;
        }
        .api-list {
            list-style-type: none;
            padding: 0;
        }
        .api-list li {
            margin: 10px 0;
            padding: 10px;
            background-color: white;
            border-radius: 3px;
            border-left: 4px solid #007bff;
        }
        .api-list code {
            background-color: #f1f1f1;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>OTA 升级文件上传系统</h1>
        
        <!-- 文件上传区域 -->
        <div class="upload-section">
            <h2>📁 文件上传</h2>
            <div class="file-input">
                <input type="file" id="fileInput" accept=".bin,.img,.tar,.gz,.zip" />
                <small>支持的文件类型: .bin, .img, .tar, .gz, .zip (最大 50MB)</small>
            </div>
            <button class="upload-btn" onclick="uploadFile()">上传文件</button>
            
            <div class="progress" id="progressContainer">
                <div class="progress-bar" id="progressBar"></div>
            </div>
            
            <div class="result" id="uploadResult"></div>
        </div>
        
        <!-- 系统状态区域 -->
        <div class="status-section">
            <h2>📊 系统状态</h2>
            <button class="refresh-btn" onclick="getStatus()">刷新状态</button>
            <div class="status-info" id="statusInfo">
                <p>点击"刷新状态"获取最新信息...</p>
            </div>
        </div>
        
        <!-- 文件列表区域 -->
        <div class="files-section">
            <h2>📋 已上传文件</h2>
            <button class="refresh-btn" onclick="getFileList()">刷新文件列表</button>
            <button class="cleanup-btn" onclick="cleanupFiles()">清理所有文件</button>
            <div class="files-list" id="filesList">
                <p>点击"刷新文件列表"查看已上传的文件...</p>
            </div>
        </div>
        
        <!-- API 说明区域 -->
        <div class="api-section">
            <h3>🔧 API 接口说明</h3>
            <ul class="api-list">
                <li><strong>文件上传:</strong> <code>POST /upload</code> - 使用 multipart/form-data 上传 OTA 文件</li>
                <li><strong>获取状态:</strong> <code>GET /cgi/ota_status</code> - 获取 OTA 系统状态信息</li>
                <li><strong>文件列表:</strong> <code>GET /cgi/ota_list</code> - 获取已上传的文件列表</li>
                <li><strong>执行升级:</strong> <code>GET /cgi/ota_install?file=filename</code> - 执行 OTA 升级</li>
                <li><strong>清理文件:</strong> <code>GET /cgi/ota_cleanup</code> - 清理所有上传的文件</li>
            </ul>
        </div>
    </div>

    <script>
        // 上传文件
        function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                showResult('请选择要上传的文件', 'error');
                return;
            }
            
            if (file.size > 50 * 1024 * 1024) {
                showResult('文件大小超过50MB限制', 'error');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            const uploadBtn = document.querySelector('.upload-btn');
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            progressContainer.style.display = 'block';
            
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showResult(`文件上传成功！文件名: ${data.filename}, 大小: ${formatBytes(data.size)}`, 'success');
                    getFileList(); // 刷新文件列表
                } else {
                    showResult(`上传失败: ${data.error}`, 'error');
                }
            })
            .catch(error => {
                showResult(`上传失败: ${error.message}`, 'error');
            })
            .finally(() => {
                uploadBtn.disabled = false;
                uploadBtn.textContent = '上传文件';
                progressContainer.style.display = 'none';
                progressBar.style.width = '0%';
            });
        }
        
        // 获取系统状态
        function getStatus() {
            fetch('/cgi/ota_status')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const statusInfo = document.getElementById('statusInfo');
                    statusInfo.innerHTML = `
                        <p><strong>上传目录:</strong> ${data.upload_dir}</p>
                        <p><strong>目录状态:</strong> ${data.upload_dir_exists ? '存在' : '不存在'}</p>
                        <p><strong>文件数量:</strong> ${data.file_count}</p>
                        <p><strong>最大上传大小:</strong> ${formatBytes(data.max_upload_size)}</p>
                        <p><strong>支持的文件类型:</strong> ${data.supported_extensions.join(', ')}</p>
                    `;
                } else {
                    document.getElementById('statusInfo').innerHTML = `<p style="color: red;">获取状态失败: ${data.error}</p>`;
                }
            })
            .catch(error => {
                document.getElementById('statusInfo').innerHTML = `<p style="color: red;">获取状态失败: ${error.message}</p>`;
            });
        }
        
        // 获取文件列表
        function getFileList() {
            fetch('/cgi/ota_list')
            .then(response => response.json())
            .then(data => {
                const filesList = document.getElementById('filesList');
                
                if (data.success) {
                    if (data.files.length === 0) {
                        filesList.innerHTML = '<p>暂无上传的文件</p>';
                    } else {
                        let html = '';
                        data.files.forEach(file => {
                            html += `
                                <div class="file-item">
                                    <div class="file-info">
                                        <div class="file-name">${file.name}</div>
                                        <div class="file-details">
                                            大小: ${formatBytes(file.size)} | 修改时间: ${file.modified}
                                        </div>
                                    </div>
                                    <button class="install-btn" onclick="installFile('${file.name}')">
                                        执行升级
                                    </button>
                                </div>
                            `;
                        });
                        filesList.innerHTML = html;
                    }
                } else {
                    filesList.innerHTML = `<p style="color: red;">获取文件列表失败: ${data.error}</p>`;
                }
            })
            .catch(error => {
                document.getElementById('filesList').innerHTML = `<p style="color: red;">获取文件列表失败: ${error.message}</p>`;
            });
        }
        
        // 执行OTA安装
        function installFile(filename) {
            if (!confirm(`确定要使用文件 "${filename}" 执行 OTA 升级吗？\n\n注意：升级过程中系统可能会重启！`)) {
                return;
            }
            
            fetch(`/cgi/ota_install?file=${encodeURIComponent(filename)}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showResult(`OTA升级已启动！\n文件: ${data.filename}\n状态: ${data.status}\n注意: ${data.note}`, 'success');
                } else {
                    showResult(`升级失败: ${data.error}`, 'error');
                }
            })
            .catch(error => {
                showResult(`升级失败: ${error.message}`, 'error');
            });
        }
        
        // 清理文件
        function cleanupFiles() {
            if (!confirm('确定要删除所有上传的文件吗？此操作无法撤销！')) {
                return;
            }
            
            fetch('/cgi/ota_cleanup')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showResult(`清理完成，已删除 ${data.deleted_files} 个文件`, 'success');
                    getFileList(); // 刷新文件列表
                } else {
                    showResult(`清理失败: ${data.error}`, 'error');
                }
            })
            .catch(error => {
                showResult(`清理失败: ${error.message}`, 'error');
            });
        }
        
        // 显示结果信息
        function showResult(message, type) {
            const resultDiv = document.getElementById('uploadResult');
            resultDiv.textContent = message;
            resultDiv.className = `result ${type}`;
            resultDiv.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                resultDiv.style.display = 'none';
            }, 5000);
        }
        
        // 格式化字节数
        function formatBytes(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 页面加载时自动获取状态和文件列表
        window.onload = function() {
            getStatus();
            getFileList();
        };
    </script>
</body>
</html>